const setting = {
	ballNum: 10,
	dVal: 10,//初始化素的范围
	g: 0.4,//重力
	f: 1.6,//阻力
}

const colors = [
	'#00b894', '#00cec9', '#0984e3', '#6c5ce7', '#d63031'
]

const stats = new Stats()
stats.showPanel(0)
document.body.appendChild(stats.dom)

const gui = new dat.GUI({ width: 320 })
const folder = gui.addFolder('基础')
folder.open()
const controller1 = folder.add(setting, 'ballNum', 10, 200, 1)
const controller2 = folder.add(setting, 'dVal', 5, 10, 1)
const controller4 = folder.add(setting, 'g', 0, 2, 0.1)
const controller5 = folder.add(setting, 'f', 0, 2, 0.1)

function initControllerGroup(controllers){
	controllers.forEach(c=>{
		c.onFinishChange(()=>{
			initBalls()
		})
	})
}
initControllerGroup([controller1,controller4,controller5,])


function Ball(x, y, dx, dy, color) {
	this.x = x
	this.y = y
	this.d = 30
	this.dx = dx
	this.dy = dy
	this.color = color

	this.draw = function () {
		noStroke()
		fill(this.color)
		circle(this.x, this.y, this.d)
	}

	this.update = function () {
		this.x += this.dx
		this.y += this.dy
		this.dy += setting.g
		//碰壁
		if (this.x - this.d / 2 < 0 || this.x + this.d / 2 > innerWidth) {
			this.dx *= -1
		this.dx = absorbEnergy(this.dx)
		}
		if (this.y - this.d / 2 < 0 || this.y + this.d / 2 > innerHeight) {
			this.dy *= -1
		this.dy = absorbEnergy(this.dy)
		}
		this.draw()
	}
}

function absorbEnergy(dVal) {
	const sign = dVal > 0 ? 1 : -1
	let result = abs(dVal) - setting.f
	result = result > 0 ? result : 0
	return result * sign
}

let balls = []

function initBalls() {
	balls = []
	for (let i = 0; i < setting.ballNum; i++) {
		const x = random(100, innerWidth - 100)
		const y = random(100, innerHeight - 100)
		const dx = random(-setting.dVal, setting.dVal)
		const dy = random(-setting.dVal, setting.dVal)
		const color = random(colors)

		const ball = new Ball(x, y, dx, dy, color)
		balls.push(ball)
	}
}

function setup() {
	createCanvas(innerWidth, innerHeight)
	initBalls()
}

function draw() {
	stats.begin()

	clear()
	background('rgba(0,0,0,1)')

	balls.forEach(ball => {
		ball.update()
	})

	stats.end()
}